<template>
  <div class="app-container">
    <!--查询-->
    <el-form :inline="true" :model="recruitQuery" class="demo-form-inline">
      <el-form-item label="计划名称">
        <el-input v-model="recruitQuery.title"></el-input>
      </el-form-item>
      <el-form-item label="职位">
        <el-select v-model="recruitQuery.positionId" filterable placeholder="请选择职位" clearable>
          <el-option
            v-for="position in positionList"
            :key="position.id"
            :label="position.name"
            :value="position.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="招聘形式">
        <el-select v-model="recruitQuery.form" style="margin-left: 10px;width: 80%" placeholder="请选择" clearable>
          <el-option
            v-for="form in employeeFormEnum"
            :key="form.value"
            :label="form.label"
            :value="form.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="recruitQuery.status" style="margin-left: 10px;width: 80%" placeholder="请选择" clearable>
          <el-option
            v-for="status in recruitStatusEnum"
            :key="status.value"
            :label="status.label"
            :value="status.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
      </el-form-item>
    </el-form>
    <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane label="我的招聘计划" name="first">
        <el-button type="primary" @click="handleAddRecruit" v-if="this.roles.includes('admin') || this.roles.includes('leader') || this.roles.includes('recruit')">创建招聘计划</el-button>
      </el-tab-pane>
      <el-tab-pane label="招聘管理" name="second" v-if="this.roles.includes('admin') || this.roles.includes('recruit')">
      </el-tab-pane>
    </el-tabs>
      <div class="block">
        <el-table :data="recruitList" style="width: 100%;margin-top:30px;" border>
          <el-table-column align="center" prop="title" label="计划名称" width="180">
            <template slot-scope="scope">
              {{ scope.row.title }}
            </template>
          </el-table-column>
          <el-table-column align="center" prop="positionId" label="职位" width="180">
            <template slot-scope="scope">
              <el-select v-model="scope.row.positionId" filterable placeholder="职位">
                <el-option
                  v-for="position in positionList"
                  :key="position.id"
                  :label="position.name"
                  :value="position.id">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="remark" label="备注" width="180">
            <template slot-scope="scope">
              {{ scope.row.remark }}
            </template>
          </el-table-column>
          <el-table-column align="center" prop="endTime" label="截至日期" width="180">
            <template slot-scope="scope">
              <el-date-picker readonly v-model="scope.row.endDate" type="date" placeholder="截至日期"></el-date-picker>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="passNum" label="通过人数" width="180">
            <template slot-scope="scope">
              {{ scope.row.passNum }}
            </template>
          </el-table-column>
          <el-table-column align="center" prop="total" label="总数" width="180">
            <template slot-scope="scope">
              {{ scope.row.total }}
            </template>
          </el-table-column>
          <el-table-column align="center" prop="total" label="招聘形式" width="180">
            <template slot-scope="scope">
              <el-select v-model="scope.row.form" style="margin-left: 10px;width: 80%" placeholder="招聘形式" disabled>
                <el-option
                  v-for="form in employeeFormEnum"
                  :key="form.value"
                  :label="form.label"
                  :value="form.value">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column align="center" label="候选人" width="180" fixed="right">
            <template slot-scope="scope">
              <el-button type="primary" @click="showCandidate(scope.row.id)">查看候选人</el-button>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="180" fixed="right">
            <template slot-scope="scope">
              <el-select v-model="scope.row.status" style="width: 100%" placeholder="请选择"
                         @change="changeStatus(scope)">
                <el-option
                  v-for="status in recruitStatusEnum"
                  :key="status.value"
                  :label="status.label"
                  :value="status.value">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
      <el-pagination
        :current-page="page"
        :page-size="limit"
        :total="total"
        style="padding: 30px 0; text-align: center;"
        layout="total, prev, pager, next, jumper"
        @current-change="getRecruits"
      />
    </div>
    <el-dialog :visible.sync="recruitDialogVisible" title="创建培训计划">
      <el-form :model="recruit" label-width="100px" label-position="left">
        <el-form-item label="面试官">
          <el-select v-model="userIds" filterable multiple placeholder="输入名字">
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.name"
              :value="user.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标题">
          <el-input v-model="recruit.title" placeholder="标题"/>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="recruit.remark" placeholder="备注"/>
        </el-form-item>
        <el-form-item label="招聘总人数">
          <el-input v-model="recruit.total" placeholder="总人数"/>
        </el-form-item>
        <el-form-item label="招聘岗位">
          <el-select v-model="recruit.positionId" filterable placeholder="请选择职位">
            <el-option
              v-for="position in positionList"
              :key="position.id"
              :label="position.name"
              :value="position.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="招聘形式">
          <el-select v-model="recruit.form" style="width: 80%" placeholder="招聘形式">
            <el-option
              v-for="form in employeeFormEnum"
              :key="form.value"
              :label="form.label"
              :value="form.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="截至时间">
          <el-date-picker
            v-model="recruit.endDate"
            type="datetime"
            value-format="yyyy-MM-ddTHH:mm:ss.000Z"
            placeholder="时间点">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="recruitDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmRecruit">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="候选人名单" :visible.sync="candidateDialogVisible" width="80%">
      <el-form :inline="true" :model="candidateQuery" class="demo-form-inline">
        <el-form-item label="状态">
          <el-select v-model="candidateQuery.status" style="margin-left: 10px;width: 80%" placeholder="请选择" clearable>
            <el-option
              v-for="status in candidateStatusEnum"
              :key="status.value"
              :label="status.label"
              :value="status.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmitCandidate">查询</el-button>
        </el-form-item>
      </el-form>
      <el-button type="primary" @click="handleAdd">添加候选人</el-button>

      <el-table :data="candidateList" style="width: 100%;margin-top:30px;" border>
        <el-table-column align="center" prop="name" label="名称" width="180">
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="total" label="性别" width="180">
          <template slot-scope="scope">
            <el-select v-model="scope.row.gender" style="margin-left: 10px;width: 80%" placeholder="性别" disabled>
              <el-option
                v-for="form in genderEnum"
                :key="form.value"
                :label="form.label"
                :value="form.value">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="email" label="邮件" width="180">
          <template slot-scope="scope">
            {{ scope.row.email }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="phone" label="电话" width="180">
          <template slot-scope="scope">
            {{ scope.row.phone }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="remark" label="描述" width="180">
          <template slot-scope="scope">
            {{ scope.row.remark }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="fileId" label="文件" fixed="right"  width="180">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="downloadFile(scope.row.fileId)">
              下载简历
            </el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope)">编辑</el-button>
            <el-select v-model="scope.row.status" style="width: 60%;margin-left: 5px" placeholder="请选择"
                       @change="changeCandidateStatus(scope)">
              <el-option
                v-for="status in candidateStatusEnum"
                :key="status.value"
                :label="status.label"
                :value="status.value">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        :current-page="page"
        :page-size="limit"
        :total="total"
        style="padding: 30px 0; text-align: center;"
        layout="total, prev, pager, next, jumper"
        @current-change="getCandidates"
      />

      <el-dialog :title="this.candidateDialogType==='new'? '添加后选人' : '编辑'" :visible.sync="dialogVisible" append-to-body>
        <el-form :model="candidate" label-width="90px" label-position="left">
          <el-form-item label="名字" v-if="candidateDialogType==='edit'">
            {{ candidate.name }}
          </el-form-item>
          <el-form-item label="名字" v-if="candidateDialogType==='new'">
            <el-input v-model="candidate.name" placeholder="名字"/>
          </el-form-item>
          <el-form-item label="邮箱" v-if="candidateDialogType==='new'">
            <el-input v-model="candidate.email" placeholder="邮箱"/>
          </el-form-item>
          <el-form-item label="电话" v-if="candidateDialogType==='new'">
            <el-input v-model="candidate.phone" placeholder="电话"/>
          </el-form-item>
          <el-form-item label="性别" v-if="candidateDialogType==='new'">
            <el-select v-model="candidate.gender" style="width: 80%" placeholder="性别">
              <el-option
                v-for="form in genderEnum"
                :key="form.value"
                :label="form.label"
                :value="form.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="candidate.remark" placeholder="描述"/>
          </el-form-item>
          <el-form-item label="简历" prop="fileId">
            <el-upload
              class="upload-demo"
              ref="upload"
              action=""
              accept="image/jpeg,image/jpg,image/png,pdf"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              :limit="1"
              :on-exceed="handleExceed"
              :file-list="fileList"
              :http-request="upload">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传pdf文件</div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div style="text-align:right;">
          <el-button type="danger" @click="dialogVisible=false">取消</el-button>
          <el-button type="primary" @click="confirmCandidate">确定</el-button>
        </div>
      </el-dialog>
      <div slot="footer" class="dialog-footer">
        <el-button @click="candidateDialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import { addRecruit, getMyRecruit, getRecruits, modifyRecruitStatus } from '@/api/recruit'
import { deepClone } from '@/utils'
import { getPositions } from '@/api/position'
import { addUser, getUserList, modifyStatus, modifyUser } from '@/api/user'
import { mapGetters } from 'vuex'
import { addCandidate, getCandidates, modifyCandidate, modifyCandidateStatus } from '@/api/candidate'
import { download, upload } from '@/api/file'
import { addUserRole } from '@/api/role'
const defaultRecruit = {}
const defaultCandidate = {}
export default {
  name: 'recruitManager',
  data() {
    return {
      recruit: Object.assign({}, defaultRecruit),
      candidate: Object.assign({}, defaultCandidate),
      recruitDialogVisible: false,
      candidateDialogVisible: false,
      dialogVisible: false,
      candidateDialogType: 'new',
      recruitList: [],
      candidateList: [],
      userList: [],
      userIds: [],
      recruitQuery: {},
      candidateQuery: {},
      positionList: [],
      recruitStatusEnum: [
        {value: 'APPLYING', label: "审核中"},
        {value: 'PASS', label: "完成"},
        {value: 'FAIL', label: "否决"},
        {value: 'RUNNING', label: "进行"},
        {value: 'END', label: "结束"}
      ],
      employeeFormEnum: [
        {value: 'SCHOOL', label: "校招"},
        {value: 'SOCIAL', label: "社招"},
        {value: 'OTHER', label: "其他"}
      ],
      candidateStatusEnum: [
        {value: 'APPLYING', label: "审核简历中"},
        {value: 'INTERVIEWING', label: "面试"},
        {value: 'FAIL', label: "否决"},
        {value: 'PASS', label: "通过"}
      ],
      genderEnum: [
        {value: 'FEMALE', label: "女"},
        {value: 'MALE', label: "男"}
      ],
      fileList: [],
      total: 100,
      page: 1,
      limit: 20,
      activeName: 'first',
    }
  },
  computed: {
    ...mapGetters([
      'roles'
    ])
  },
  created() {
    this.getRecruits()
    this.getPositionList()
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const res = await getUserList()
      this.userList = res.data
    },
    async getRecruits(page = 1) {
      const offset = this.limit * (page - 1);
      let res;
      if (this.activeName === 'first'){
        res = await getMyRecruit(this.recruitQuery, offset, this.limit)
      } else {
        res = await getRecruits(this.recruitQuery, offset, this.limit)
      }
      this.recruitList = res.data.rows
      this.total = res.data.total
    },
    onSubmit() {
      this.getRecruits()
    },
    onSubmitCandidate() {
      this.getCandidates()
    },
    async getPositionList() {
      const res = await getPositions()
      this.positionList = res.data
    },
    changeStatus({ $index, row }){
      this.$confirm('确定要修改状态吗?', 'Warning', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await modifyRecruitStatus(row.id, row.status)
          // this.userList.splice($index, 1)
          this.$message({
            type: 'success',
            message: '修改状态成功!'
          })
        })
        .catch(err => {
          console.error(err)
        })
    },
    handleAddRecruit() {
      this.recruit = Object.assign({}, defaultRecruit)
      this.userIds = []
      this.recruitDialogVisible = true
    },
    async confirmRecruit() {
      this.recruit.userIds = this.userIds
      await addRecruit(this.recruit)
      await this.getRecruits()
      this.recruitDialogVisible = false
      this.$notify({
        title: 'Success',
        dangerouslyUseHTMLString: true,
        message: '操作成功',
        type: 'success'
      })
    },
    handleClick(tab, event) {
      this.getRecruits()
    },
    async showCandidate(id) {
      this.candidateDialogVisible = true
      this.candidateQuery.recruitId = id
      await this.getCandidates()
    },
    async getCandidates(page = 1) {
      const offset = this.limit * (page - 1);
      const res = await getCandidates(this.candidateQuery, offset, this.limit)
      this.candidateList = res.data.rows
      this.total = res.data.total
    },
    async downloadFile(fileName) {
      await download(fileName).then(res => {           //定义文件名等相关信息
        const blob = res
        const reader = new FileReader()
        reader.readAsDataURL(blob)
        reader.onload = (e) => {
          const a = document.createElement('a')
          a.download = fileName
          a.href = e.target.result
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
        }
      })
    },
    handleEdit(scope) {
      this.candidate = deepClone(scope.row)
      this.dialogVisible = true
      this.candidateDialogType = 'edit'
    },
    handleAdd() {
      this.candidate = Object.assign({}, defaultCandidate)
      this.dialogVisible = true
      this.candidateDialogType = 'new'
      this.candidate.recruitId = this.candidateQuery.recruitId
      this.fileList = []
    },
    async confirmCandidate() {
      const isEdit = this.candidateDialogType === 'edit'
      if (isEdit) {
        await modifyCandidate(this.candidate.id, this.candidate)
        for (let index = 0; index < this.candidateList.length; index++) {
          if (this.candidateList[index].id === this.candidate.id) {
            this.candidateList.splice(index, 1, Object.assign({}, this.candidate))
            break
          }
        }
      } else {
        await addCandidate(this.candidate)
      }
      this.dialogVisible = false
      await this.getCandidates()
      this.$notify({
        title: 'Success',
        dangerouslyUseHTMLString: true,
        message: "操作成功",
        type: 'success'
      })
    },
    changeCandidateStatus({ $index, row }) {
      this.$confirm('确定要修改状态吗?', 'Warning', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await modifyCandidateStatus(row.id, row.status)
          // this.userList.splice($index, 1)
          this.$message({
            type: 'success',
            message: '修改状态成功!'
          })
        })
        .catch(err => {
          console.error(err)
        })
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      this.candidate.fileId = ''
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    async upload(params) {
      let form = new FormData();
      this.$refs.upload.uploadFiles.forEach((file) => {
        form.append("file", file.raw);
      });
      await upload(form).then((res) => {
        this.candidate.fileId = res.data
        // console.log(this.contract.fileId)
      })
    }
  }
}
</script>

<style scoped>

</style>
